package com.b2c.repository.ecom;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.ecom.GoodsImgDataEntity;
import com.b2c.entity.ecom.GoodsStyleDataEntity;
import com.b2c.entity.ecom.GoodsStyleReferEntity;

@Repository
public class GoodsStyleReferRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Transactional
    public PagingResponse<GoodsStyleReferEntity> getList(Integer pageIndex, Integer pageSize,String platform,String type) {
                StringBuilder sb = new StringBuilder();
                sb.append("SELECT SQL_CALC_FOUND_ROWS kw.*");
               
                sb.append(" FROM ecom_goods_style_refer as kw ");
                sb.append(" where kw.isDelete=0 ");
        
                List<Object> params = new ArrayList<>();
                if (StringUtils.isEmpty(type) == false) {
                    sb.append(" AND kw.`type` = ?  ");
                    params.add(type);
                }
                if (StringUtils.isEmpty(platform) == false) {
                    sb.append(" AND kw.platform = ?");
                    params.add(platform);
                }
               
                
        
                sb.append(" ORDER BY kw.id DESC LIMIT ?,? ");
                params.add((pageIndex - 1) * pageSize);
                params.add(pageSize);
        
                List<GoodsStyleReferEntity> list = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(GoodsStyleReferEntity.class), params.toArray(new Object[params.size()]));
                Integer totalSize = getTotalSize();
                return new PagingResponse<>(pageIndex, pageSize, totalSize, list);
    }

    protected int getTotalSize() {
        return jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);
    }

    public void add(GoodsStyleReferEntity entity) {
        String sql ="INSERT INTO ecom_goods_style_refer (title,url,img,platform,`date`,source,`type`,remark) VALUE (?,?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql, entity.getTitle(),entity.getUrl(),entity.getImg(),entity.getPlatform(),entity.getDate(),entity.getSource(),entity.getType(),entity.getRemark());
    }
}
